package net.arogarth.aws.android.manager.views;

import java.util.ArrayList;
import java.util.List;

import net.arogarth.aws.android.lib.AmazonEc2;
import net.arogarth.aws.android.lib.AwsRequestException;
import net.arogarth.aws.android.lib.models.Ec2Ami;
import net.arogarth.aws.android.manager.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Ec2AmiList extends Activity {
	public class Ec2AmiListAdapter extends BaseAdapter {

		private final List<Ec2Ami> images = new ArrayList<Ec2Ami>();

		private Context context;

		public Ec2AmiListAdapter(Context view, ListView list) {
			this.context = view;

			list.setAdapter(this);
//			list.setOnItemLongClickListener(new ListClickListener());
			
			this.loadData();
		}

		private void loadData() {
			final ProgressDialog pd = ProgressDialog.show(this.context,
					"Bitte warten...", "Daten werden geladen...", true, false);

			Thread t = new Thread() {
				public void run() {
					AmazonEc2 aec2 = new AmazonEc2();
					try {
						List<Ec2Ami> _instances = aec2.describeImages();
						for (Ec2Ami instance : _instances) {
							images.add(instance);
						}

						handler.sendEmptyMessage(0);
					} catch (final AwsRequestException e) {
						runOnUiThread(new Runnable() {
							public void run() {
								Toast.makeText(context, e.getMessage(),
										Toast.LENGTH_SHORT).show();
								finish();
							}
						});
					}
				}

				private Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {

						notifyDataSetChanged();

						pd.dismiss();
					}
				};
			};
			t.start();
			//
		}

		public int getCount() {
			return this.images.size();
		}

		public Ec2Ami getItem(int arg0) {
			return (Ec2Ami) this.images.get(arg0);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final Ec2Ami image = (Ec2Ami) getItem(position);

			final LinearLayout _ll = (LinearLayout) LayoutInflater.from(
					this.context).inflate(R.layout.ec2_ami_list_item,
					parent, false);

			((TextView) _ll.findViewById(R.id.imageId)).setText(image.getName());
			((TextView) _ll.findViewById(R.id.tvPlatform)).setText(image
					.getPlatform());

			return _ll;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.basic_list);
		final ListView lv = (ListView) findViewById(R.id.contentlist);
		new Ec2AmiListAdapter(Ec2AmiList.this, lv);
	}
}
